<?php
namespace control;
// 维修领用
class aftermarketCollocationClass extends adIndexClass
{

	private const page           = 'aftermarketCollocation';
	private const table          = 'parts_inventory';
	private const tableMx        = 'parts_inventory_detail';
	private const tableTarget    = 'material';
	private const tableInv       = 'inventory';
	private const tableInvMx     = 'inventory_detail';
	private const tableInvRecord = 'inventory_record';
	private const title          = '维修领用';
	private const state          = ['制单', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '领用单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'staff' => [
                        'name'  => "领用人",
                        'width' => 200,
                    ],
                    'department'  => [
                        'name'  => "领用人部门",
                        'width' => 200,
                    ],
                    'sourceId'  => [
                        'name'  => "关联维修单号",
                        'width' => 200,
                    ],
                    'stid'  => [
                        'name'  => "制单人",
                        'width' => 200,
                    ],
                    'orderDate'         => [
                        'name'  => '领用日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "领用单号" => text(array("name" => "orderNO")),
                    "领用人"   => selectMultiple(["name" => "targetId[]", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'multiple' => true]),
                    '领用人部门' => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name']),
                ],
                [
                    '制单人'  => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    "领用日期" => text(array("name" => "orderDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url     = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$where = " coid = '" . self::$coid . "' AND classify=0 ";
		$equal = [
			'orderNO' => $this->post('orderNO'),
			'stid'    => $this->post('stid'),
			'state'   => $this->post('state'),
		];

		$like = [
			'targetId' => !static::is_null_array($this->post('targetId')) ? implode(',', $this->post('targetId')) : '',
		];
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url     = root . "control/adIndex.html?cla=" . self::page;
		$isPrint = $this->power(self::page, "print");
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate   = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
				"edit"   => $array['state'] !== '已确认' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
				'print'  => ($isPrint === true) ? ['title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"] : [],
			);
			$targetArr  = explode(',', $array['targetId']);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'staff':
                        $staff      = $targetArr ? self::findStaff($targetArr) : '';
                        $row[] = $staff;
                        break;
                    case 'department':
                        $department = $targetArr ? self::findStaffDepartment($targetArr) : '';
                        $row[] = $department;
                        break;
                    case 'sourceId':
                        $sourceId   = self::getSourceOrderNo($array);
                        $row[] = $sourceId;
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
		$tr[]     = ['', '编码', '配件名称', '规格', '单位', '仓库名称', '仓位', '批号', '库存', '数量', '备注'];

		$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
        $totalArr = ['orderNum'=>0,'num'=>0];
		foreach ($result['array'] as $k=>$array) {
			$material          = query(self::tableTarget, " id = '$array[partsId]'  ");
			$hiddenHtml        = hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
			                     hidden(['name' => 'orderNum[]', 'value' => $array['orderNum']]) .
			                     hidden(['name' => 'unit[]', 'value' => $array['unit']]) .
			                     hidden(['name' => 'warehouseId[]', 'value' => $array['warehouseId']]) .
			                     hidden(['name' => 'materialId[]', 'value' => $array['partsId']]) .
			                     hidden(['name' => 'batch[]', 'value' => $array['batch'],]) .
			                     hidden(['name' => 'positionId[]', 'value' => $array['positionId'],]);
			$tr[]              =
				[
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
					$hiddenHtml,
					$material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    warehouseClass::getName($array['warehouseId']),
                    warehousePositionClass::getName($array['positionId']),
                    $array['batch'],
                    "<span class='orderNum'>".self::lostZero($array['orderNum'],'numPrecision')."</span>",
					text(['name' => 'num[]', 'blur' => 'calculateTotal', 'value' => self::lostZero($array['num'],'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]),
                    text(['name' => 'mxText[]', 'value' => $array['text'],]),
				];
            $totalArr['orderNum'] += $array['orderNum'];
            $totalArr['num'] += $array['num'];
		}
        $total = [
            8 => "<span id='total_orderNum'>".self::lostZero($totalArr['orderNum'],'numPrecision')."</span>",
            9 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
        ];
		$list  = $this->listTable(['tr' => $tr, 'end' => true, 'total' => $total]);
		$page  = self::page;
        $mxButton = <<<EOT
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">选择配件</span>
EOT;
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '领用人'   =>
                        selectMultiple(["name" => "targetId[]", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '领用人', 'value' => $info['targetId'], 'multiple' => true]),
                    must . '领用日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]),
                    '关联维修单号'    => selectMultiple([
                        "name" => "sourceId[]",
                        'table' => "aftermarket",
                        'sqlId' => 'id',
                        'sqlField' => 'orderNo',
                        'title' => '维修单号',
                        'value' => $info['sourceId'],
                        "where" => " coid = '" . self::$coid . "' AND workFlow IN ('登记', '派工')  ",
                        'multiple' => true
                    ]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '选择明细',
            'button' => $mxButton,
            'html' => $list,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<EOT
<script>

function addRow(){
    const mxIdArr = []
    $("input:checkbox[name='mxId[]']:checked").each(function() {
        mxIdArr.push($(this).val())
    })
   	if(mxIdArr.length > 0){
	    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit', $("form[name='mxForm']").serialize(), function(res) {
	        $("#materialTable tbody").append(res.html);
	        resetNumber($("#materialTable"))
	        calculateTotal()
	    },'json')
   	}
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let num = 0,
    orderNum = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var orderNumText = table.find(".orderNum").eq(index).text()
        if(orderNumText){
            orderNum+=Number(orderNumText);
        }
    })
    $("#total_orderNum").text(orderNum.toFixed(publicSettings.numPrecision.num));
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
}
</script>
EOT;
		//返回
		return $this->tab($data);
	}

	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: [];
		$materialIdArr    = $this->post('materialId');
		$warehouseIdArr   = $this->post('warehouseId');
		$positionIdArr    = $this->post('positionId');
		$batchArr         = $this->post('batch');
		$orderNumArr      = $this->post('orderNum');
		$numArr           = $this->post('num');
		$unitArr          = $this->post('unit');
		$mxTextArr        = $this->post('mxText');

		$field      = [
			'targetId'  => $this->post('targetId') ? self::filterArray($this->post('targetId')) : [],
			'orderDate' => $this->post('orderDate'),
			'sourceId'  => $this->post('sourceId'),
			'text'      => $this->post('text'),
		];
		$annotation = [
			'targetId'  => '领用人',
			'orderDate' => '领用日期',
			'text'      => '备注',
		];
		$rules      = [
			'targetId'  => 'required',
			'orderDate' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = '请选择领用明细';
		} elseif (static::is_null_array($materialIdArr)) {
			$json['warn'] = '请选择领用明细';
		} elseif (static::is_null_array($numArr)) {
			$json['warn'] = '数量请填写完整';
		} elseif (static::is_null_array($warehouseIdArr)) {
			$json['warn'] = '请选择仓库';
		} elseif (static::is_null_array($orderNumArr)) {
			$json['warn'] = '库存数量填写完整';
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = '此领用单已确认，不能修改';
		} else {
			$this->startTrans();
			$isPass               = true;//事务通过标志
			$field['targetId']    = implode(',', $field['targetId']);
			$field['sourceId']    = $field['sourceId'] ? implode(',', $field['sourceId']) : '';
			$field['sourceTable'] = $field['sourceId'] ? 'aftermarket' : '';
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'OSOU' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'       => $id,
					'orderNo'  => $orderNo,
					'classify' => 0,
					'state'    => '制单',
					'coid'     => self::$coid,
					'stid'     => $this->control['stid'],
				]);
				$json['warn'] = static::insert([
					"table" => self::table,
					"field" => $field,
				]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新领用单明细
			foreach ($mxIdArr as $k => $nid) {
				$mx          = query(self::tableMx, "id = '$nid'");
				$material    = query(self::tableTarget, "id = '$materialIdArr[$k]'");
				if (static::isNull($material['id'])) {
					continue;
				}
                $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                $orderNumArr[$k] = self::formattingFigure($orderNumArr[$k],'numPrecision');
				if ($numArr[$k] > $orderNumArr[$k]) {
					$json['warn'] = '【' . $material['name'] . '】领用数量不能大于库存数量';
					goto resp;
				}
				$price = inventoryBalanceClass::unitPrice($materialIdArr[$k]);
				if (!empty($mx['id'])) {
					//更新
					$warn = static::update([
						"table" => self::tableMx,
						"field" => [
							'partsId'     => $material['id'],
							'num'         => $numArr[$k],
							'orderNum'    => $orderNumArr[$k],
							'price'       => $price,
							'money'       => self::formattingFigure($price * $numArr[$k]),
							'warehouseId' => $warehouseIdArr[$k],
							'positionId'  => $positionIdArr[$k],
							'batch'       => $batchArr[$k],
							'text'        => $mxTextArr[$k],
						],
						"where" => " id = '$nid'",
					]);
				} else {
					//新增
					$warn = static::insert([
						"table" => self::tableMx,
						"field" => [
							'id'          => $nid,
							'coid'        => self::$coid,
							'orderId'     => $id,
							'partsId'     => $material['id'],
							'num'         => $numArr[$k],
							'orderNum'    => $orderNumArr[$k],
							'unit'        => $unitArr[$k],
							'price'       => $price,
							'money'       => self::formattingFigure($price * $numArr[$k]),
							'warehouseId' => $warehouseIdArr[$k],
							'positionId'  => $positionIdArr[$k],
							'batch'       => $batchArr[$k],
							'text'        => $mxTextArr[$k],
						],
					]);
				}
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$isPass       = false;
					$json['warn'] = $warn;
					break;
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx(): bool|string
	{
		$tableMx = $this->post('tableMx');
		$html    =
			selectMultiple([
			    'table' => 'warehouse',
                "title" => '选择仓库',
                'sqlField' => 'name',
                'sqlId' => 'id',
                "where" => " coid = '" . self::$coid . "' and state = '启用' ",
                'name' => 'warehouseId'
            ])
			. text(["name" => "type", "title" => "类别"])
			. text(["name" => "name", "title" => "配件名称"])
			. text(["name" => "model", "title" => "规格型号"])
			. hidden(["name" => "tableMx", 'value' => $tableMx])
			. hidden(['name' => 'materialId', 'value' => implode(',', (array)$this->post('materialId'))])
			. hidden(['name' => 'orderId', 'value' => $this->post('orderId')]);
		$button  = "<input style='margin-left: 5px' onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub' value='提交'>";
		$html    = $this->search($html);
		return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
	}

	/**
	 *添加物料
	 */
	public function addMxSearch(): bool|string
	{
		$materialId = $this->post('materialId') ? explode(',', $this->post('materialId')) : [];
		$where      = " m.id = r.materialId and m.coid = '" . self::$coid . "' and m.id not in ('" . implode("','", $materialId) . "')";
		$like       = [
			'm.name'  => $this->post('name'),
			'm.code'  => $this->post('code'),
			'm.model' => $this->post('model'),
			'm.typeName' => $this->post('type'),
		];
		$equal      = [
			'm.state'       => '启用',
			'r.warehouseId' => $this->post('warehouseId'),
		];
		$fieldArr   = self::resolveField([
			'field' => ' m.code, m.name, m.typeId, m.typeName, m.model, m.unit, m.time, r.materialId, r.positionId, r.warehouseId, r.batch',
			'group' => ' r.materialId, r.warehouseId, r.positionId, r.batch',
		]);
		$where      .= search(["like" => $like, "=" => $equal]) . $fieldArr['group'];
		$page       = $this->page([
			"table" => self::tableTarget . ' as m, ' . self::tableInvRecord . ' as r',
			'field' => $fieldArr['field'] . ', IFNULL(sum(r.num),0) as total',
			"where" => $where . ' HAVING total > 0',
			"order" => " time desc",
		]);
		//获取表头
		$checkAll = $this->checkAll("mxForm", "mxId");
		$tr[]     = [$checkAll, '类别', '编码', '配件名称', '规格', '单位', '仓库名称', '仓位', '批次', '库存数量'];
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate          = [
				"box" => ["name" => "mxId", "value" => $array['materialId'],],
			];
			$xid               = self::getId();
			$tr[]              = [
				$this->dominate($dominate) .
				hidden(['name' => $array['materialId'], 'value' => $xid]) .
				hidden(['name' => 'materialId[' . $xid . ']', 'value' => $array['materialId']]) .
				hidden(['name' => 'warehouseId[' . $xid . ']', 'value' => $array['warehouseId']]) .
				hidden(['name' => 'positionId[' . $xid . ']', 'value' => $array['positionId']]) .
				hidden(['name' => 'batch[' . $xid . ']', 'value' => $array['batch']]),
				$array['typeName'],
				$array['code'],
				$array['name'],
				$array['model'],
				$array['unit'],
				warehouseClass::getName($array['warehouseId']),
				warehousePositionClass::getName($array['positionId']),
				$array['batch'],
				self::lostZero($array['total'],'numPrecision'),
			];
		}
		$json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(["tr" => $tr, "showSort" => true, "page" => $page['para']]) . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit(): bool|string
	{
		$mxIdArr     = $this->post('mxId');
		$warehouseId = $this->post('warehouseId');
		$batch       = $this->post('batch');
		$positionId  = $this->post('positionId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$tr = [];
			foreach ($mxIdArr as $k => $mxId) {
                $material          = query(self::tableTarget, "id = '$mxId'");
				if (static::isNull($material['id'])) {
					continue;
				}
				// 序号
				$xid               = $this->post($material['id']);

				$warehouse         = query('warehouse', " id = '$warehouseId[$xid]' ", 'id, name');
				$warehousePosition = query('warehouse_position', " id = '$positionId[$xid]' ", 'name');
				$inventoryNum      = self::lostZero(inventoryBalanceClass::inventoryNum($mxId, $warehouseId[$xid], $positionId[$xid], $batch[$xid]),'numPrecision');
				$id                = self::getId();
				$hiddenHtml        = hidden(['name' => 'mxId[]', 'value' => $id]) .
				                     hidden(['name' => 'orderNum[]', 'value' => $inventoryNum]) .
				                     hidden(['name' => 'unit[]', 'value' => $material['unit']]) .
				                     hidden(['name' => 'warehouseId[]', 'value' => $warehouse['id']]) .
				                     hidden(['name' => 'positionId[]', 'value' => $positionId[$xid]]) .
				                     hidden(['name' => 'materialId[]', 'value' => $material['id']]) .
				                     hidden(['name' => 'batch[]', 'value' => $batch[$xid],]);
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    $hiddenHtml,
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $warehouse['name'],
                    $warehousePosition['name'],
                    $batch[$xid],
                    "<span class='orderNum'>".$inventoryNum."</span>",
                    text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'type' => 'text', 'other' => self::digitalFiltering('numPrecision'), 'value' => '')),
                    text(array('name' => 'mxText[]')),
                ];
			}
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}

	public static function getSourceOrderNo($info): string
	{
		$sourceId = '';
		if ($info['sourceId'] && $info['sourceTable']) {
			$ids = self::filterArray(explode(',', $info['sourceId']));
			foreach ($ids as $id) {
				$target   = query($info['sourceTable'], " id = '$id' ", 'orderNo');
				$sourceId .= (!static::isNull($target['orderNo'])) ? $target['orderNo'] . ',' : '';
			}
			$sourceId = rtrim($sourceId, ',');
		}
		return $sourceId;
	}

	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
				if ($info['state'] == '制单') {
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
						'style' => 'li-btn-blue-bg',
					];
					//按钮
					$button[] = [
						"name" => "提交",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'commit', "id" => $info['id']],
					];
				}
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => "确认",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name" => "取消",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
            //操作记录
            $button[] = self::operateLogBut($info['id']);

			$mxtr[] = ['编码', '产品名称', '规格', '单位', '仓库名称', '仓位', '批次', '库存', '数量', '备注'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            $totalArr = ['orderNum'=>0,'num'=>0];
			foreach ($result['array'] as $array) {
				$material          = query(self::tableTarget, " id = '$array[partsId]'");
				$mxtr[]            = [
					$material['code'],
					$material['name'],
					$material['model'],
					$material['unit'],
					warehouseClass::getName($array['warehouseId']),
					warehousePositionClass::getName($array['positionId']),
					$array['batch'],
					self::lostZero($array['orderNum'], 'numPrecision'),
                    self::lostZero($array['num'], 'numPrecision'),
					$array['text'],
				];
                $totalArr['orderNum'] += $array['orderNum'];
                $totalArr['num'] += $array['num'];
			}
            $total_tr = [
                7=>$totalArr['orderNum']?self::lostZero($totalArr['orderNum'],'numPrecision'): 0,
                8=>$totalArr['num']?self::lostZero($totalArr['num'],'numPrecision'): 0,
            ];
			// 关联维修单
			$sourceId = self::getSourceOrderNo($info);
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				'基本信息' => [
					[
						"领用人"       => self::findStaff(explode(',', $info['targetId'])),
						"领用日期"     => $info['orderDate'],
						'关联维修单号' => $sourceId,
                        "领用单号" => $info['orderNo'],
					],
                    [
                        "制单人"   => self::findStaff($info['stid']),
                        "状态"     => $info['state']
                    ],
					[
						"备注" => $info['text'],
					]
				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '领用明细',
                'html' => $this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 确认
	 */
	public function confirmEdit(): bool|string
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '已确认',
			'confirmTime' => $this->time,
		];
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此领用单';
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = '此领用单不是待确认状态，不能确认';
		} else {
			$this->startTrans();
			$isPass       = true; // 事务通过标志
			$json['warn'] = static::update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
				$oid   = self::getId();
				$field = [
					'id'          => $oid,
					'type'        => '其他出库',
					'subCategory' => '配件领用',
					'orderDate'   => $this->date,
					'text'        => '配件领用单：' . $info['orderNo'],
					'orderNo'     => codeTemplateClass::generateCode('outStockOther',[
                        'prefix' => 'QTRK' . date('Ymd'),
                        'table'  => self::tableInv,
                        'field'  => 'orderNo',
                        'where'  => " AND coid = '" . self::$coid . "' ",
                    ],[]),
					'classify'    => 0,
					'warehouseId' => '0000',
					'state'       => '待出库',
					'coid'        => self::$coid,
					'stid'        => $this->control['stid'],
					'sourceTable' => self::table,
					'sourceId'    => $info['id'],
					'sourceDate'  => $info['orderDate'],
					'sourceNo'    => $info['orderNo'],
					'commitTime'  => $this->time,
				];
				$bool  = static::insert(["table" => self::tableInv, "field" => $field,]);
				if ($bool != '新增成功') {
					$json['warn'] = '确认失败';
					goto resp;
				}

				$details = find([
					'table' => self::tableMx,
					'where' => " orderId = '{$info['id']}'",
				]);
				foreach ($details['array'] as $value) {
					static::insert([
						'table' => self::tableInvMx,
						'field' => [
							'id'            => self::getNo(),
							'coid'          => self::$coid,
							'orderId'       => $oid,
							'materialId'    => $value['partsId'],
							'warehouseId'   => $value['warehouseId'],
							'positionId'    => $value['positionId'],
							'batch'         => $value['batch'],
							'orderNum'      => abs($value['num']),
							'num'           => 0,
							'price'         => abs($value['price']),
							'money'         => abs($value['money']),
							'unit'          => $value['unit'],
							'sourceTable'   => 'parts_inventory_detail',
							'sourceId'      => $value['id'],
							'text'          => $value['text'],
						],
					]);
				}
				$this->commitTrans();//提交事务
				auditingFollow([
					"type"   => "配件领用",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】确认",
				]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 取消
	 */
	public function cancelEdit(): bool|string
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'      => '制单',
			'commitTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有取消权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此领用单';
		} elseif ($info['state'] == '已确认') {
			$json['warn'] = '此领用单是已确认状态，无法取消';
		} else {
			$json['warn'] = static::update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow(array(
					"type"   => "配件领用",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】取消",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit(): bool|string
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'      => '待确认',
			'commitTime' => $this->date,
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此领用单';
		} elseif ($info['state'] != '制单') {
			$json['warn'] = '此领用单不是制单状态，不能提交';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow([
					"type"   => "配件领用",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】提交",
				]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act   = $this->post('act') ?? '';
		$pwd   = $word = false; // 需要密码
		$power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此领用单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此领用单？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认取消此领用单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					delete(["table" => self::tableMx, "where" => " orderId = '$id' "]);
					delete(["table" => 'auditing_follow', "where" => " typeId = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
		$info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
		$info['title']       = self::title;
		$info['printTime']   = $this->time;
		$info['stid']        = self::findStaff($info['stid']);
		$info['targetId']    = self::findStaff(explode(',', $info['targetId']));
		$info['qr']          = "source=" . self::page . "&id=" . $info['id'];
        $info['warehouseId'] = warehouseClass::getName($info['warehouseId']);
		$detail              = find(['table' => self::tableMx, 'where' => " orderId = '$info[id]' order by time asc"])['array'];
		$items               = [];
		$x                   = 1;
		$totalNum            = $totalPrice = $totalMoney = 0;
		foreach ($detail as $array) {
			$material            = query(self::tableTarget, "id = '$array[partsId]'");

			$total               = self::formattingFigure($array['price'] * $array['num']);
			$items[]             = [
				'no'          => $x,
				'code'        => $material['code'],
				'name'        => $material['name'],
				'model'       => $material['model'],
				'num'         => self::lostZero($array['num'],'numPrecision'),
				'warehouseId' => warehouseClass::getName($array['warehouseId']),
				'price'       => self::lostZero($array['price'],'pricePrecision'),
				'money'       => $total,
				'text'        => $array['text'],
			];
			$x++;
			$totalPrice += $array['price'];
			$totalMoney += $total;
			$totalNum   += $array['num'];
		}
		$append         = [
			'no'    => '合计',
			'num'   => self::lostZero($totalNum,'numPrecision'),
			'price' => self::lostZero($totalPrice,'pricePrecision'),
			'money' => self::lostZero($totalMoney),
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}

}
